#include "lm75.h"

int getAnalogueInput(int channel) {
	//start conversion now (for selected channel)
	ADCR = (ADCR & 0xFFFFFF00) | (1 << channel) | (1 << 24);
	//wait til done
	while((ADDR & 0x80000000) == 0);
	//get result and adjust to 10-bit integer
	return (ADDR>>6) & 0x3FF;
}

void initLM75() {
	IOSET0 = (1<<30);
	IODIR0 |= (1<<7) |(1<<8) |(1<<9) | (1<<30);
	PINSEL1 |= 0x01000000; // 1 na 24 bicie = AD1
	//initialize ADC
	ADCR = (1 << 1)                             |  //SEL = 1, dummy channel #1
		 ((CRYSTAL_FREQUENCY *
		   PLL_FACTOR /
		   VPBDIV_FACTOR) / 4500000 - 1) << 8 |  //set clock division factor, so ADC clock is 4.5MHz (~12,3)
		 (0 << 16)                            |  //BURST = 0, conversions are SW controlled
		 (0 << 17)                            |  //CLKS  = 0, 11 clocks = 10-bit result
		 (1 << 21)                            |  //PDN   = 1, ADC is active
		 (1 << 24)                            |  //START = 1, start a conversion now
		 (0 << 27);							     //EDGE  = 0, not relevant when start=1

	osSleep(1);
	int integerResult = ADDR; //must be
}

int readTemperature() {
	int temp = getAnalogueInput(1);
	return 0.176 * temp - 55;
}
